import React, {Component} from 'react'
import {View, Text, FlatList, TouchableOpacity} from 'react-native'
import Loading from '../common/loading_common'
import {GetTextBooksApi} from '../../config/api'
import FastImage from 'react-native-fast-image'
import styles, {GREY, SMALL} from '../../config/styles'

class BookList extends Component {
    constructor (props) {
        super(props);
        this.state = {
            data: [],
            loading: true
        }
    }

    componentDidMount () {
       this.getData()
    }

    getData = () => {
        this.setState({loading: true}, () => {
            GetTextBooksApi().then((data) => {
                if (data.code == 0) {
                    this.setState({
                        data: data.data,
                        loading: false
                    })
                }
            })
        })
    }

    //用于sectionlist的key
    _keyExtractor = (item, index) => index

    _renderItem = ({item}) => {
        const {navigation} = this.props
        return (
            <TouchableOpacity 
                onPress={() => navigation.navigate('chapters_list', {textbook_id: item.id})}
                style={{flex: 1, flexDirection: 'row', padding: 10, margin: 5, backgroundColor: 'white'}}>
                <View>
                    <FastImage
                        style={{width: 100, height: 100}}
                        source={{ uri: item.cover_url,  priority: FastImage.priority.normal }}
                        //resizeMode="contain"
                    />
                </View>
                <View style={{flex: 1, padding: 10}}>
                    <View>
                        <Text>{item.name}</Text>
                    </View>
                    <View style={{flex: 1, justifyContent: 'center'}}>
                        <Text style={{color: GREY, fontSize: SMALL}}>{item.description}</Text>
                    </View>
                </View>
            </TouchableOpacity>
        )
    }

    render () {
        const {loading, data} = this.state
        if (loading == true) {
            return (<Loading />)
        } else {
            return (
                <FlatList
                    data={data}
                    keyExtractor={this._keyExtractor}
                    renderItem={this._renderItem}
                    refreshing={loading}
                    onRefresh={this.getData}
                    style={{flex: 1}}
                />
            )
        }
        
    }
}

export default BookList